package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author lubiao
 * @date 2021/5/5
 * @desc Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端⼝号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的⼀些操作
     */
    public void start() throws Exception {
        /**
         * 完成Minicat 1.0版本
         * 需求：浏览器请求http://localhost:8080,返回⼀个固定的字符串到⻚⾯"Hello Minicat!"
         */
        /*ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
       /* while (true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源⽂件
         */
        /*ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            //从输入流当中获取请求
            int available = 0;
            while(available == 0){
                available = inputStream.available();
            }
            byte[] bytes = new byte[available];
            inputStream.read(bytes);
            System.out.println("=====>>>请求信息："+new String(bytes));
            socket.close();
        }*/

        /*ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            //封装Request对象和Response
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());

            socket.close();
        }*/

        /**
         * 完成Minicat 3.0版本
         * 需求：请求动态资源（Servlet）
         */
        // 加载解析相关的配置，web.xml
        /*loadServlet();
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            //封装Request对象和Response
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            HttpServlet httpServlet = servletMap.get(request.getUrl());
            //静态资源处理
            if(httpServlet == null){
                response.outputHtml(request.getUrl());
            }else{//动态资源servlet请求
                httpServlet.service(request,response);
            }

            socket.close();
        }*/

        /**
         * 完成Minicat 3.1版本
         * 需求：多线程改造
         */
        // 加载解析相关的配置，web.xml
        /*loadServlet();
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.start();
        }*/

        /**
         * 完成Minicat 3.2版本
         * 需求：多线程改造2(线程池)
         */
        // 加载解析相关的配置，web.xml
        loadServlet();
        //定义一个线程池
        int corePoolSize = 10;          // 核心线程数（维持线程池的基本线程数）
        int maximumPoolSize = 50;       // 线程池的大小
        long keepAliveTime = 100L;      // 线程存活时间（不干活的就销毁）
        TimeUnit unit = TimeUnit.SECONDS;           //时间单位
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);      //请求队列
        ThreadFactory threadFactory = Executors.defaultThreadFactory();  //线程工厂
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); //拒绝策略

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,unit,workQueue,threadFactory,handler);
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    /**
     * Minicat的程序入口
     * @param args
     */
    public static void main(String[] args) {
        try {
            new Bootstrap().start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String,HttpServlet> servletMap = new HashMap<>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();//<web-app>
            List<Element> servletNodes = rootElement.selectNodes("//servlet");
            for (Element servletNode : servletNodes) {
                Element servletNameElement = (Element) servletNode.selectSingleNode("servlet-name"); //<servlet-name>minicat</servlet-name>
                String servletName = servletNameElement.getStringValue();//minicat
                Element servletClassElement = (Element) servletNode.selectSingleNode("servlet-class");//<servlet-class>server.MyServlet</servlet-class>
                String servletClass = servletClassElement.getStringValue();//server.MyServlet

                //根据servlet-name找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern =servletMapping.selectSingleNode("url-pattern").getStringValue(); // /minicat

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
